package com.dcy.daily.skill.rabbitMQ.springAMQP.tmp.messageOrder;

import com.dcy.daily.common.config.annotation.ComponentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * https://docs.spring.io/spring-amqp/docs/current/reference/html/#multi-strict
 * 测试用例
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年07月29日 17:16
 */
@ComponentUtil.CComponent
public class MessageOrderUsage{

    private static final Logger log = LoggerFactory.getLogger(MessageOrderUsage.class);

    @Bean
    TaskExecutor exec() {
        ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
        exec.setCorePoolSize(10);
        return exec;
    }

    /**
     * MQ连接工厂
     * @return
     */
    @Bean
    CachingConnectionFactory ccf() {
        CachingConnectionFactory ccf = new CachingConnectionFactory();
        ccf.setHost("centos-node-135");
        ccf.setUsername("guest");
        ccf.setPassword("guest");
        ccf.setPort(5672);
        CachingConnectionFactory publisherCF = (CachingConnectionFactory) ccf.getPublisherConnectionFactory();
        //设置channel缓存为1，保证使用同一个channel且在队列中的消息排序。
        publisherCF.setChannelCacheSize(1);
        publisherCF.setChannelCheckoutTimeout(1000L);
        return ccf;
    }

    /**
     * 消费queue队列中的消息
     * @param in
     */
    @RabbitListener(queues = "queue")
    void listen(String in) {
        log.info(in);
    }

    /**
     * 声明队列queue
     * @return
     */
    @Bean
    Queue queue() {
        return new Queue("queue");
    }


    /**
     * 发送消息
     * @param service
     * @param exec
     * @return
     */
    @Bean
    public ApplicationRunner runner(Service service, TaskExecutor exec) {
        return args -> {
            exec.execute(() -> service.mainService("test"));
        };
    }

}
